package com.cvmars.jianyou.module.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cvmars.jianyou.R;
import com.cvmars.jianyou.api.api.Api;
import com.cvmars.jianyou.api.api.HttpUtils;
import com.cvmars.jianyou.api.api.SimpleSubscriber;
import com.cvmars.jianyou.api.model.HttpResult;
import com.cvmars.jianyou.model.ReadStatus;
import com.cvmars.jianyou.model.UserCoustomModel;
import com.cvmars.jianyou.model.UserModel;
import com.cvmars.jianyou.module.activity.MessageActivity;
import com.cvmars.jianyou.module.activity.PersonHomeActivity;
import com.cvmars.jianyou.module.adapter.UserGuanzhuAdapter;
import com.cvmars.jianyou.module.base.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.rong.imkit.fragment.ConversationListFragment;
import io.rong.imlib.model.Conversation;

/**
 * Created by hehaifeng on 2018/12/1.
 */

public class ChatIMFragment extends BaseFragment {


    @BindView(R.id.list_guanzhu)
    RecyclerView listGuanzhu;
    Unbinder unbinder;
    UserGuanzhuAdapter homeAdapter;
    List<UserModel> list = new ArrayList<>();
    @BindView(R.id.iv_notice_message)
    ImageView ivNoticeMessage;
    @BindView(R.id.view_status)
    TextView viewStatus;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.frag_im_chat, null);
        unbinder = ButterKnife.bind(this, view);
        listGuanzhu.setLayoutManager(new LinearLayoutManager(getContext()
                , LinearLayoutManager.HORIZONTAL, false));

        homeAdapter = new UserGuanzhuAdapter(getActivity(), R.layout.item_guanzhu, list);

        homeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

//                getActivity().startActivity(new Intent(getActivity(), ChatIMDetailActivity.class));
                String userId = list.get(position).id;
                onGoHome(userId);
//                String name  = list.get(position).name;
//                RongIM.getInstance().startPrivateChat(getActivity(), userId, name);
            }
        });
        listGuanzhu.setAdapter(homeAdapter);


//        RongIM.getInstance().startConversationList(getContext());


        //会话列表
        ConversationListFragment conversationListFragment = new ConversationListFragment();
        Uri uri = Uri.parse("rong://" + getActivity().getApplicationInfo().packageName).buildUpon()
                .appendPath("conversationlist")
                .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false") //设置私聊会话，该会话聚合显示
                .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "false")
                .appendQueryParameter(Conversation.ConversationType.SYSTEM.getName(), "true")//设置系统会话，该会话非聚合显示
                .build();
        conversationListFragment.setUri(uri);

        FragmentManager fragmentManager = getChildFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.rong_container, conversationListFragment);
        transaction.commit();

//        if(fragments == null){
//
//            fragments =new ConversationListFragment();
//
//            //动态添加到布局中，注意replace中的第一个参数为activity_main中的id
//
//            getChildFragmentManager().beginTransaction().replace(R.id.conversationlist,fragments).commit();
//        }

//        ConversationListFragment fragments = ConversationListFragment.instantiate()
//        Uri uri = Uri.parse("rong://" + getActivity().getApplicationInfo().packageName).buildUpon()
//                .appendPath("conversationlist")
//                .appendQueryParameter(Conversation.ConversationType.PRIVATE.getName(), "false")
//                .appendQueryParameter(Conversation.ConversationType.GROUP.getName(), "false")
//                .appendQueryParameter(Conversation.ConversationType.DISCUSSION.getName(), "false")
//                .appendQueryParameter(Conversation.ConversationType.SYSTEM.getName(), "false")
//                .build();
//
//        fragments.setUri(uri);
        requestData();
        return view;
    }


    int mCurPage = 1;

    public void requestData() {


        HttpUtils.getInstance().toSubscribe(Api.getInstance().getUserTimeList(mCurPage)
                , new SimpleSubscriber<HttpResult<UserCoustomModel>>() {
                    @Override
                    protected void _onNext(HttpResult<UserCoustomModel> o) {


                        UserCoustomModel data = o.getData();
                        if (data != null) {
                            List<UserModel> results = data.results;
                            list.clear();
                            list.addAll(results);
                            homeAdapter.notifyDataSetChanged();
                        }

                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }


    @Override
    public void onResume() {
        super.onResume();
        requestStatusData();
        requestData();
    }

    //获取阅读状态
    public void requestStatusData() {


        HttpUtils.getInstance().toSubscribe(Api.getInstance().getReadStatus()
                , new SimpleSubscriber<HttpResult<ReadStatus>>() {
                    @Override
                    protected void _onNext(HttpResult<ReadStatus> o) {


                        ReadStatus data = o.getData();
                        if (data != null) {

                            viewStatus.setVisibility(data.unread_count > 0 ? View.VISIBLE : View.GONE);

                            if(data.unread_count > 99){

                                viewStatus.setText("99");
                            }else{

                                viewStatus.setText(data.unread_count+"");

                            }
                        }

                    }

                    @Override
                    protected void _onError(String message) {

                    }
                });
    }


    private void onGoHome(String id) {

        Intent intent = new Intent(getActivity(),
                PersonHomeActivity.class);
        intent.putExtra("userid", id);
        startActivity(intent);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick(R.id.iv_notice_message)
    public void onViewClicked() {
        viewStatus.setVisibility(View.GONE);
        getActivity().startActivity(new Intent(getActivity(), MessageActivity.class));
    }
}
